package cn.shiro.shiroservice.auth.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentMap;

/**
 * &#064;Time 2024 一月 星期三 18:25
 *
 * @author ShangGuan
 * 将SessionId放在缓存中
 */
@Slf4j
public class ISessionManager extends AbstractSessionDAO {

    private final RedisTemplate<Object, Object> cache;


    public ISessionManager(RedisTemplate<Object, Object> cache) {
        this.cache = cache;
    }


    //序列化方法
    @Override
    protected Serializable doCreate(Session session) {
        final Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        log.info("Session saved to cache with ID: {}", session.getId());
        cache.opsForValue().set(sessionId, session);
        return sessionId;
    }

    /**
     * 读取
     *
     * @param sessionId 会话id
     * @return {@link Session}
     */
    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = (Session) cache.opsForValue().get(sessionId);
        if (session == null || session.getId() == null) {
            log.warn("Session read cache 失效");
            throw new SessionException("Session read cache 失效");
        }
        log.info("Session read to cache with ID: {}", session.getId());
        return session;

    }

    //缓存更新
    @Override
    public void update(Session session) throws UnknownSessionException {
        if (session == null ) {
            log.warn("Session update cache 失效");
            throw new SessionException("Session update cache 失效");
        }
        Serializable sessionId = session.getId();
        if(sessionId==null){
            log.warn("Session update cache 失效");
            throw new SessionException("Session update cache 失效");
        }
        log.info("Session update to cache with ID: {}", sessionId);
        cache.opsForValue().set(sessionId, session);
    }

    //删除缓存
    @Override
    public void delete(Session session) {
        Serializable sessionId = session.getId();
        if (session == null || session.getId() == null) {
            log.warn("Session update cache 失效");
            throw new SessionException("Session update cache 失效");
        }
        log.info("Session delete to cache with ID: {}", session.getId());
        cache.delete(sessionId);
    }

    @Override
    public Collection<Session> getActiveSessions() {
        // 获取所有活跃的 Session
        // 这里可以返回空集合，因为我们已经通过 Redis 存储了 Session
        return Collections.emptySet();
    }
}
